package com.whereta.controller;

import com.whereta.service.IMenuService;
import com.whereta.service.IMessageBoardService;
import com.whereta.service.IPermissionService;
import com.whereta.vo.MessageBoardCreateVO;
import com.whereta.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author Vincent
 * @time 2015/8/12 13:49
 */
@Controller
@RequestMapping("/main")
public class MainController {
    @Resource
    private IMenuService menuService;
    @Resource
    private IPermissionService permissionService;
    @Resource
    private IMessageBoardService messageBoardService;

    //跳转到主页
    @RequestMapping("/index")
    public String index() {
        return "main/index";
    }


    //获取显示权限
    @RequestMapping("/get-show-permissions")
    public
    @ResponseBody
    ResultVO getShowPermissons() {
        ResultVO resultVO = permissionService.getShowPermissions(null);
        return resultVO;
    }

    //获取显示权限
    @RequestMapping("/get-show-permissions-except-children")
    public
    @ResponseBody
    ResultVO getShowPermissonsExceptChildren(@RequestParam Integer perId) {
        ResultVO resultVO = permissionService.getShowPermissions(perId);
        return resultVO;
    }

    //获取菜单显示权限
    @RequestMapping("/get-menu-show-permissions")
    public
    @ResponseBody
    ResultVO getMenuShowPermissons(@RequestParam int menuId) {
        ResultVO resultVO = permissionService.getMenuShowPermissions(menuId);
        return resultVO;
    }

    //获取角色显示权限
    @RequestMapping("/get-role-show-permissions")
    public
    @ResponseBody
    ResultVO getRoleShowPermissons(@RequestParam int roleId) {
        ResultVO resultVO = permissionService.getRoleShowPermissions(roleId);
        return resultVO;
    }

    //跳转到欢迎页面
    @RequestMapping("/welcomePage")
    public String welcomePage() {
        return "main/welcomePage";
    }

    //保存用户留言内容
    @RequestMapping(value = "/save-message-board", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO saveMessageBoard(@Valid @ModelAttribute final MessageBoardCreateVO vo, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        ResultVO resultVO = new ResultVO(true);

        if (fieldErrors != null && !fieldErrors.isEmpty()) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            resultVO.setOk(false);
            resultVO.setMsg(defaultMessage);
            return resultVO;
        }
        Object principal = SecurityUtils.getSubject().getPrincipal();
        resultVO = messageBoardService.saveMessageBoard(Integer.parseInt(principal.toString()), vo.getMsg());
        return resultVO;
    }
}
